<!--
 * @Author: Neil 1294641898@qq.com
 * @Date: 2022-09-05 19:58:47
 * @LastEditors: Neil 1294641898@qq.com
 * @LastEditTime: 2022-09-06 19:48:14
 * @FilePath: \stupid_home\src\views\communication\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div :class="[communication,lightStyle]"  >
    <van-nav-bar
    left-text="返回"
    left-arrow
    @click-left="goBack"
    />
    <div class="header">
      <div class="headerTxt">{{equip_name}}</div>
      <div class="lightbox">
        <img v-if="isLightOpen" @click="closeLight" src="../../../public/light-off-50.png" alt="">
        <img v-else  @click="openLight" src="../../../public/light-on-50.png" alt="">
        
      </div>
    </div>
    <div v-if="countDownCloseShow" class="countDown">
      <van-count-down millisecond  v-if="isSetTimeClose" :time="closetime" format="HH:mm:ss:SS" />
      <van-count-down
        ref="countDown"
        millisecond
        :time="closetime()"
        :auto-start="true"
        format="HH:mm:ss:SS"
        @finish="closefinsh"
      />
    </div>
    <van-dialog v-model="setTimeCloseShow" @confirm="showCloseCountDown" title="定时关灯" show-cancel-button>
      <van-datetime-picker
        v-model="currentTimeClose"
        type="time"
        :min-minute="1"
        :show-toolbar=false
        :columns-order="['hour','minute']"
        :formatter="formatter"
      />
    </van-dialog>
    <div   class="setTimelight" style="margin-bottom:30px">
      <div  class="setTime">
        <van-button type="default" @click="()=>{setTimeCloseShow=true}">定时关灯</van-button>
      </div>
      <div class="openButton">
        <van-button type="default" @click="()=>{isLightOpen = false;sendMsg('LED_OFF');}">立刻关灯</van-button>
      </div>
    </div>
    <!-- 开灯部分 -->
    <div v-if="countDownOpenShow" class="countDown">
      <van-count-down millisecond  v-if="isSetTimeOpen" :time="opentime" format="HH:mm:ss:SS" />
      <van-count-down
        ref="countDown"
        millisecond
        :time="closetime()"
        :auto-start="true"
        format="HH:mm:ss:SS"
        @finish="openfinsh"
      />
    </div>
    <van-dialog v-model="setTimeOpenShow" @confirm="showOpenCountDown" title="定时开灯" show-cancel-button>
      <van-datetime-picker
        v-model="currentTimeOpen"
        type="time"
        :min-minute="1"
        :show-toolbar=false
        :columns-order="['hour','minute']"
        :formatter="formatter"
      />
    </van-dialog>
    <div class="setTimelight" style="margin-top:30px">
      <div  class="setTime">
        <van-button type="default" @click="()=>{setTimeOpenShow=true}">定时开灯</van-button>
      </div>
      <div class="openButton">
        <van-button type="default" @click="()=>{isLightOpen = true;sendMsg('LED_ON');}">立刻开灯</van-button>
      </div>
    </div>
    <div class="door">
      <div class="doorAnimation">
        <div class="doorTxt">Doo</div>
        <div class="doorTxt controlR" :class="isOpenAnimation?'openAnimate':'doorTxt controlR'" @animationend='isOpenAnimation=false'>r</div>
        
      </div>
      <van-button :round="true" type="default" @click="() => { isOpenAnimation = true; sendMsg('OPEN_DOOR')}">开门</van-button>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  props: {},

  data() {
      return {
          token: "",
          org_id: "",
          equip_id: "",
        equip_name: "",
        // 全局唯一socket 
        socket: null,
        // 定时开关ms数

        // 控制贴图切换 
        isLightOpen: true,
        // 用于彩蛋 
        communication: "communication",
        lightStyle: "openStyle",
        //控制定时器组件是否显示
        isSetTimeOpen:false,
        isSetTimeClose: false,
        //控制倒计时输入框
        setTimeOpenShow:false,
        setTimeCloseShow: false,
        currentDate: new Date(),
        //初始定时时间
        currentTimeClose: '00:01',
        countDownCloseShow:false,
        currentTimeOpen: '00:01',
        countDownOpenShow: false,
        isOpenAnimation: false,
        // 每次建立通信查询灯的初始状态 
        origin_status:""
        
        
        
    };
  },
  watch: {
    // firstName(newName, oldName) {
    //   this.fullName = newName + ' ' + this.lastName;
    // }
  },
  computed: {},
  methods: {
    createSocket() {
      if (this.socket == null) {
        let random_token = Date.now();
        var wsUri =`wss://cloud.alientek.com/connection/${this.token}/org/${this.org_id}?token=` + random_token; 
        this.socket = new WebSocket(wsUri);
        
        // 初次连接订阅消息并查询状态 
        this.socket.onopen = () => {
          this.subscribeDeviceInfo()
          this.sendMsg('STATUS')
        }
        this.socket.onmessage = (e) => {
          var reader = new FileReader();
          reader.onload = () => {
            if (reader.result.length != 0) {
              this.origin_status = reader.result.substring(21);//内容就在这里
              if (this.origin_status == "true") {
                this.isLightOpen=true
              } else if (this.origin_status == "false") {
                this.isLightOpen=false
              }
              // console.log(this.isLightOpen,"初始值设置");
            }
            // console.log(this.origin_status,this.origin_status.length,typeof this.origin_status,"reader");
          };
          reader.readAsText(e.data);
        }
      }
        return this.socket
    },
    //订阅设备消息，用于获取灯的状态
    subscribeDeviceInfo() {
      let arr = new Int8Array(21);
        arr[0] = 1;
        for(let i = 0; i < this.equip_id.length; i++){
            arr[i + 1] = this.equip_id[i].charCodeAt(0);
        }
        this.socket.send(arr)
      },
     sendMsg(msg) {
        console.log(msg,this.socket);
        let arr = new Int8Array(21+msg.length);
        arr[0] = 3;
        for(let i = 0; i < this.equip_id.length; i++){
            arr[i + 1] = this.equip_id[i].charCodeAt(0);
        }
        for (let i = 0,j=21; i < msg.length; i++,j++) {
            arr[j]=msg[i].charCodeAt(0)     
        }
      //  this.socket.onopen=()=>{
      //     console.log("建立连接");
      //  }
       if (this.socket.readyState == 1) {
         this.socket.send(arr)
       } else if (this.socket.readyState == 3) {
          console.log("连接已断开");
        }
        
    },
    getRouterData() {
        this.token = localStorage.getItem("token")  
        this.org_id = localStorage.getItem("org_id")    
        this.equip_id = localStorage.getItem("equip_id")     
      this.equip_name = localStorage.getItem("equip_name")  
        console.log(this.token,this.org_id,this.equip_id,this.equip_name);   
        },
    goBack() {
        console.log(this.socket);
        this.socket.close()
        this.$destroy();
        this.$router.push('/device')
    },
    openLight() {
      this.lightStyle="openStyle"
      this.isLightOpen = true;
      this.sendMsg('LED_ON');
    },
    closeLight() {
      this.isLightOpen = false
      this.lightStyle="closeStyle"
      this.sendMsg('LED_OFF');
      console.log(this.lightStyle);
    },
    formatter(type, val) {
      if (val[0] == '0') {
        val=val[1]
      }
      if (type === 'hour') {
        return val + '小时';
      }
      if (type === 'minute') {
        return val + '分钟';
      }
      return val;
    },
    // 关灯计时器三件套
    closefinsh() {
      this.$toast('倒计时结束,已关灯');
      this.countDownCloseShow = false
      this.closeLight()
    },
    closetime() {
      let [hour, minute] = this.currentTimeClose.split(":")
      return (parseInt(hour)*60+parseInt(minute))*60*1000
    },
    showCloseCountDown() {
      console.log("showCloseCountDown");
      this.countDownCloseShow=true
    },
    //开灯计时器三件套
    openfinsh() {
      this.$toast('倒计时结束，已开灯');
      this.countDownOpenShow = false
      this.openLight()
    },
    opentime() {
      let [hour, minute] = this.currentTimeOpen.split(":")
      return (parseInt(hour)*60+parseInt(minute))*60*1000
    },
    showOpenCountDown() {
      console.log("showCloseCountDown");
      this.countDownOpenShow=true
    }
  },

  mounted() {
      this.getRouterData()
      this.createSocket()
      this.isLightOpen=false
  }
};
</script>
<style lang="less" scoped>
    .communication{
    width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  // color: #fff;
  .header{
    margin: 60px 0;
    display: flex;
    justify-content: space-around;
    
    .headerTxt{
      font-size: 40px;
      font-weight: 700;
      line-height: 54px;
    }
  }
  .door{
    margin: 60px 0;
    display: flex;
    justify-content: space-around;
    .doorAnimation{
      position: relative;
      .doorTxt{
        font-size: 40px;
        font-weight: 700;
        line-height: 54px;
      }
      .controlR{
        position: absolute;
        top:0px;
        left:80px;
      }
      .openAnimate{
        animation-direction:alternate-reverse;
        animation: openDoor cubic-bezier(0.165, 0.84, 0.44, 1)2s ;
      }
    }
  }
  .setTimelight{
    display: flex;
    justify-content: space-around;
  }
  .van-count-down{
    line-height: 54px;
    font-size: 30px;
  }
}
.openStyle{
  background-color: #fff;
  color:#000
}
.closeStyle{
  background-color: #000;
  color:#fff
}
@keyframes openDoor
{
  from {top:0px;left: 80px;color: #000;}
  to {top:0px;left: 150px;color: #eee;}
}
</style>